var net = require('net');
var fs = require('fs')
var readline = require('readline');
var path = __dirname + '/../DATA_20180720/DATA_20180720/DATA_20180720_rover_2_10';

var client = new net.Socket();

client.connect(8146, '127.0.0.1', function () {
    var data = fs.readFileSync(path + '/' + 'rover.txt');
    // console.log(data.toString())
    // var dataArr = data.toString().split('\\');
    // var i = 0
    // var setTime = setInterval(function () {
    //     client.write(dataArr[i])
    //     i++;
    //     if (i === dataArr.length) {
    //         clearInterval(setTime)
    //     }
    // }, 1000)

    var lines = []
    var myInterface = readline.createInterface({
        input: fs.createReadStream(path + '/' + "rover.txt")
    });
    myInterface.on('line', function (line) {
        var index = line.split(',');
        lines.push(line)
    });
    myInterface.on('close', function () {
        var avr = [];
        var key;

        var start = 0;
        var end = 10;

        for (var i = 0; i < lines.length / 10; i++) {

            var arr = lines.slice(start, end);

            avr.push(arr.join('\r\n'));

            start += 10;
            end += 10

            //     var line = lines[i].split(',');
            //     if (line.length < 5) {
            //         continue;
            //     }
            //
            //     if (line[4].indexOf("BEG*") !== -1 && line[1] ==="#1") {
            //         key = line[1];
            //         continue
            //     }
            //
            //     if (line[1] === ("AVR") && key === "#1") {
            //         avr.push(lines[i]);
            //     }else {
            //         key = undefined;
            //     }
        }

        var n = 0;

        var setTime = setInterval(function () {
            client.write(avr[n]);
            n++;
            if (n === avr.length) {
                clearInterval(setTime)
            }
        }, 100)
    })
});

client.on('data', function (data) {
    console.log('Received: ' + data);
    // client.destroy();
});

client.on('close', function () {
    console.log('Connection closed');
});